<?php
/**
 * DBShop 电子商务系统
 *
 * ==========================================================================
 * @link      https://www.dbshop.net/
 * @copyright 北京珑大钜商科技有限公司，并保留所有权利。
 * @license   https://www.dbshop.net/license.html License
 * ==========================================================================
 *
 * @author    静静的风 <baron@loongdom.cn>
 *
 */

namespace Shop\Validator;

use Laminas\I18n\Translator\Translator;
use Laminas\Validator\AbstractValidator;
use Operation\Entity\RechargeCode;
use Operation\Entity\RechargeCodeRule;

class UserRechargeCodeValidator extends AbstractValidator
{
    const NOT_SCALAR        = 'notScalar';
    const CODE_NOT_EXISTS   = 'codeNotExists';
    const CODE_NOT_START    = 'codeNotStart';
    const CODE_EXPIRED      = 'codeExpired';
    const CODE_USED         = 'codeUsed';

    protected $options = [
        'entityManager',
        'rechargeCodeRule'
    ];

    protected $messageTemplates = [];

    public function __construct($options = null)
    {
        if(isset($options['entityManager']))    $this->options['entityManager']     = $options['entityManager'];

        $trans = new Translator();
        $this->messageTemplates = [
            self::NOT_SCALAR        => $trans->translate("这不是一个标准输入值"),
            self::CODE_NOT_EXISTS   => $trans->translate("该充值码不存在"),
            self::CODE_NOT_START    => $trans->translate("该充值码还没有到可充值时间"),
            self::CODE_EXPIRED      => $trans->translate("该充值码已过期"),
            self::CODE_USED         => $trans->translate("该充值码已被使用")
        ];

        parent::__construct($options);
    }

    public function isValid($value)
    {
        if(!is_scalar($value)) {
            $this->error(self::NOT_SCALAR);
            return false;
        }

        $rechargeCodeInfo = $this->options['entityManager']->getRepository(RechargeCode::class)->findOneBy(['codeStr' => $value]);
        if ($rechargeCodeInfo == null) {
            $this->error(self::CODE_NOT_EXISTS);
            return false;
        }
        if ($rechargeCodeInfo->getUserId() > 0) {
            $this->error(self::CODE_USED);
            return false;
        }

        $rechargeCodeRule = $this->options['entityManager']->getRepository(RechargeCodeRule::class)->findOneBy(['codeRuleId' => $rechargeCodeInfo->getCodeRuleId()]);
        if ($rechargeCodeRule->getCodeRuleState() < 1) {
            $this->error(self::CODE_NOT_EXISTS);
            return false;
        }
        if ($rechargeCodeRule->getCodeStartTime() > 0 && $rechargeCodeRule->getCodeStartTime() > time()) {
            $this->error(self::CODE_NOT_START);
            return false;
        }
        if ($rechargeCodeRule->getCodeEndTime() > 0 && $rechargeCodeRule->getCodeEndTime() < time()) {
            $this->error(self::CODE_EXPIRED);
            return false;
        }

        return true;
    }
}